import { useLocation, useNavigate, type To, type NavigateOptions } from 'react-router-dom';

export const useHistory = () => {
  const location = useLocation();
  const navigater = useNavigate();
  const params = new URLSearchParams(location.search);
  //转为对象
  const obj: any = {};
  params.forEach((value, key) => {
    obj[key] = value;
  });

  const navigate = (path: To, options?: NavigateOptions) => {
    let newPath = path;
    try {
      if (typeof path === 'object'
        && Object.prototype.toString.call(path) === '[object Object]'
        && Object.prototype.toString.call(path.search) === '[object Object]') {
        newPath = {
          ...path,
          search: new URLSearchParams(path.search).toString(),
        };
      }
    } catch (error) {

    }
    navigater(newPath, options);
  };
  return {
    location: { ...location, query: obj },
    navigate
  };
};